<?php
namespace App\Http\Controllers\RESTfulApi;

use Illuminate\Routing\Controller;

use App\Models\hwtc\Apiuser;  //这里改为api登录模型！
use Illuminate\Http\Request;
use App\Libraries\Logs;

class BaseapiController extends Controller
{
//    use Helpers;


    /****
     * BaseController constructor.
     */
    public function __construct()
    {

    }

    //登录
    public function authenticate(Request $request)
    {
        if(!empty(file_get_contents("php://input")) && json_decode(file_get_contents("php://input"),true) != ''){
            $payload=json_decode(file_get_contents("php://input"),true);
        } else {
            $payload = [
                'name' => $request->get('name'),
                'password' => $request->get('password')
            ];    
        }
        
        try {
            if (!$token = JWTAuth::attempt($payload)) {

                Logs::setLog($_SERVER['REQUEST_URI'],
                    array('status_code'=>401,'message'=>'error','data'=>'token_not_provided'),
                    $payload);

                return APIReturn(401,'error','token_not_provided');
            }
        } catch (JWTException $e) {

            Logs::setLog($_SERVER['REQUEST_URI'],
                array('status_code'=>403,'message'=>'error','data'=>'不能创建token'),
                $payload);
            return APIReturn(403,'error','不能创建token');
        }
        
        //查找用户角色 和权限
        $current_user=Apiuser::with(['apiroles'=>function($query){
            $query->select('name','display_name');
        }])->where('name',trim($payload['name']))->first();

        $apiroles=$current_user->apiroles->toArray();
//        return $apiroles;
        if(count($apiroles)==0){
            //说明一个角色都没有赋予  提示无权限！
            return APIReturn(402,'error','您没有权限执行此操作！');
        }

        foreach($current_user->apiroles as $apirole){
            unset($apirole['pivot']);
        }

        //查找用户所有权限
//        $permissions=Apiuser::get_apiuser_permissions($current_user);
        //end查找用户角色 和权限

        Logs::setLog($_SERVER['REQUEST_URI'],
            array('status_code'=>200,'message'=>'success','data'=>array_merge(compact('token'),['roles'=>$current_user->apiroles->toArray()])),
            $payload);
        return APIReturn(200,'success',array_merge(compact('token'),['roles'=>$current_user->apiroles->toArray()]));
    }

//    注册
    public function register(Request $request)
    {
        $newUser = [
            'name' => $request->get('name'),
            'password' => bcrypt($request->get('password'))
        ];
        $user = Apiuser::create($newUser);
        $token = JWTAuth::fromUser($user);
        return $token;
    }

    /****
     * 获取用户的信息
     */
    public function AuthenticatedMe()
    {
        try {
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                return APIReturn(404,'error',['user_not_found']);
//                return response()->json(['user_not_found'], 404);
            }
        } catch (TokenExpiredException $e) {
            return APIReturn($e->getStatusCode(),'error',['token_expired']);
//            return response()->json(['token_expired'], $e->getStatusCode());
        } catch (TokenInvalidException $e) {
            return APIReturn($e->getStatusCode(),'error',['token_invalid']);
//            return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (JWTException $e) {
            return APIReturn($e->getStatusCode(),'error',['token_absent']);
//            return response()->json(['token_absent'], $e->getStatusCode());
        }
        // the token is valid and we have found the user via the sub claim

        Logs::setLog($_SERVER['REQUEST_URI'], array('status_code'=>200,'message'=>'success','data'=>compact('user')));
        return APIReturn(200,'success',compact('user'));
    }
}